<?php

abstract class Controller {

  protected $action;
  protected $response;

  public function __construct($action) {
    $this->action = $action;
    $this->response = new Response();
  }

  public abstract function validate();

  public function render() {
    header("Content-Type:application/json");
    echo '{"success":"true","result":';
    echo json_encode($this->response->getValues());
    echo "}";
  }

  public function renderErrors() {
    header("Content-Type:application/json");
    echo '{"success":"false","errors":' . json_encode($this->response->getErrors()) . "}";
  }

  public function execute() {

    $this->validate();
    if ($this->response->hasError()) {
      $this->renderErrors();
      return;
    }

    $this->action->validate($this->response);
    if ($this->response->hasError()) {
      $this->renderErrors();
    }

    $this->action->execute($this->response);
    if ($this->response->hasError()) {
      $this->renderErrors();
    } else {
      $this->render();
    }
  }

}

?>